package com.hangwei.paperless;

import android.Manifest;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hangwei.paperless.fragment.sub.SubBaseInfoFragment;
import com.hangwei.paperless.fragment.sub.SubBatchFragment;
import com.hangwei.paperless.fragment.sub.SubDataFragment;
import com.hangwei.paperless.fragment.sub.SubPartCheckFragment;
import com.hangwei.paperless.fragment.sub.SubProcessListFragment;
import com.hangwei.paperless.fragment.sub.SubSetListFragment;
import com.hangwei.paperless.fragment.sub.SubWorkStepFragment;
import com.hangwei.paperless.model.bean.CardToSeal;
import com.hangwei.paperless.model.bean.DataFilling;
import com.hangwei.paperless.presenter.StaticPresenter;
import com.hangwei.paperless.utils.Density;
import com.hangwei.paperless.utils.NFCCallBack;
import com.hangwei.paperless.view.SubProgressTitle;
import com.hangwei.paperless.widget.CardSealPop;
import com.hangwei.paperless.widget.MainBottomPopupWindow;
import com.hangwei.paperless.widget.MainListPopupWindow;
import com.hangwei.paperless.widget.PicDialog;
import com.twelve.all.base.BaseFragment;
import com.twelve.all.base.NFCApp;
import com.twelve.all.net.CallBack;
import com.twelve.all.nfc.BasicActivity;
import com.twelve.all.nfc.Constants;
import com.twelve.all.nfc.MCReader;
import com.twelve.all.nfc.PreferencesUtil;
import com.twelve.all.nfc.Utils;
import com.twelve.all.utils.LoadingDialog;
import com.twelve.all.utils.LogUtil;
import com.twelve.all.utils.SPKey;
import com.twelve.all.utils.SPUtil;
import com.twelve.all.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 张龙臣 on 2020/11/27.
 */

public class SubRepairActivity extends BasicActivity implements View.OnClickListener, SubProgressTitle.OnProgressItemClickListener {

    public static String pwoNo;
    private ImageView mIvList;
    private boolean mIsLotDataSheet;
    private SubProgressTitle mSubProgressTitle;

    public void setStepId(String stepId) {
        this.stepId = stepId;
    }

    private String stepId;
    private NFCCallBack mNFCCallBack;
    private CardSealPop mCardSealPop;
    private boolean mCanCard;
    private String mWoNo;
    private String mPn;
    private String mSn;
    private String mDescription;
    public static String mApn;

    public String getBillId() {
        return mBillId;
    }

    private String mBillId;

    public void setStep(String step) {
        if (TextUtils.isEmpty(step))
            mStep = "0";
        else
            mStep = step;
        int index = 0;
        try {
            String[] split = mStep.split("-");
            index = Integer.parseInt(split[0]);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mSubProgressTitle.setProgressStep(index);
        }
    }

    public String getStep() {
        return mStep;
    }

    private String mStep;
    private MainBottomPopupWindow mMainBottomPopupWindow;
    private LoadingDialog mDialog;
    public static String mStepId;
    private MainListPopupWindow mPopupWindow;
    private PicDialog mPicDialog;

    @Override
    public void onBackPressed() {
        if (mSubProgressTitle != null && mSubProgressTitle.getStep() > 3) {
            mSubProgressTitle.setProgressStep(3);
            setCurrentPage(String.valueOf(3));
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        mApn = null;
        mStepId = null;
        pwoNo = null;
        super.onDestroy();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub_repair);
        mIvList = (ImageView) findViewById(R.id.ivList);
        TextView tvBaseWorkCard = (TextView) findViewById(R.id.tvBaseWorkCard);
        TextView tvPN = (TextView) findViewById(R.id.tvPN);
        TextView tvSN = (TextView) findViewById(R.id.tvSN);
        TextView tvDes = (TextView) findViewById(R.id.tvDes);
        LinearLayout back = (LinearLayout) findViewById(R.id.back);
        FrameLayout progressContent = findViewById(R.id.progressContent);

        back.setOnClickListener(this);
        mIvList.setOnClickListener(this);

        Intent intent = getIntent();
        mBillId = intent.getStringExtra("id");
        mStep = intent.getStringExtra("step");
        mIsLotDataSheet = intent.getBooleanExtra("isLotDataSheet", false);
        mWoNo = intent.getStringExtra("woNo");
        mPn = intent.getStringExtra("pn");
        mSn = intent.getStringExtra("sn");
        mDescription = intent.getStringExtra("description");
        tvBaseWorkCard.setText(mWoNo);
        tvPN.setText(mPn);
        tvSN.setText(mSn);
        tvDes.setText(mDescription);

        mSubProgressTitle = new SubProgressTitle(this);
        int index = 0;
        try {
            String[] split = mStep.split("-");
            index = Integer.parseInt(split[0]);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mSubProgressTitle.setProgressStep(index);
        }
        setCurrentPage(mStep);
        mSubProgressTitle.setL(this);
        mSubProgressTitle.setIsLotData(mIsLotDataSheet);
        progressContent.addView(mSubProgressTitle.getInflate());
    }


    public void showTrans() {
        mSubProgressTitle.setTrans(true);
    }

    public void setCurrentPage(String step) {
        String current = "0";
        try {
            String[] split = step.split("-");
            current = split[0];
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if ("100".equals(step)) {//转交
                tansformProcessList();
            } else {
                BaseFragment fragment = null;
                switch (current) {
                    case "0":
                        fragment = new SubBaseInfoFragment();
                        break;
                    case "1":
                        fragment = new SubWorkStepFragment();
                        break;
                    case "2":
                        fragment = new SubBatchFragment();
                        break;
                    case "3":
                        fragment = new SubDataFragment();
                        break;
                    case "4":
                        fragment = new SubPartCheckFragment();
                        break;
                    case "5":
                        fragment = new SubSetListFragment();
                        break;
                    case "6":
                        fragment = new SubProcessListFragment();
                        break;
                }
                if (fragment != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("billId", mBillId);
                    bundle.putString("step", mStep);
                    fragment.setArguments(bundle);
                    getSupportFragmentManager().beginTransaction().replace(R.id.flContainer, fragment).commit();
                }
            }
        }
    }

    private void tansformProcessList() {
        LoadingDialog loadingDialog = new LoadingDialog(this);
        loadingDialog.show();
        String userId = SPUtil.getString(SPKey.Account.USER_ID);
        StaticPresenter.transferTechnician(userId, stepId, new CallBack<Object>() {
            @Override
            public void onCompleted(Object o) {
                loadingDialog.dismiss();
                ToastUtil.showCenterToast("转交成功！");
            }

            @Override
            public void onError() {
                loadingDialog.dismiss();
                ToastUtil.showCenterToast("转交失败！");
            }
        });
    }

    public MainBottomPopupWindow showBottomPopupWindow(BottomPopType type, String subId) {
        View inflate = initPopView(type);
        mMainBottomPopupWindow = new MainBottomPopupWindow(this, inflate, type);
        if (type == BottomPopType.NA) {
            mMainBottomPopupWindow.setOnNAListener(new MainBottomPopupWindow.OnNAListener() {
                @Override
                public void onNA(String stampId, String naTypeId) {
                    sealByCard("", new NFCCallBack() {
                        @Override
                        public void onCallBack(List<CardToSeal.StampBean> stampIds, String userId) {
                            if (stampIds == null || stampIds.size() == 0) {
                                ToastUtil.showCenterToast("无印章！");
                            } else {
                                String userId0 = SPUtil.getString(SPKey.Account.USER_ID);
                                if (mDialog == null)
                                    mDialog = new LoadingDialog(SubRepairActivity.this);
                                if (!mDialog.isShowing()) mDialog.show();
                                StaticPresenter.stampNAInfo(userId0, mBillId, subId, userId, stampIds.get(0).stampId, naTypeId, new CallBack<Object>() {
                                    @Override
                                    public void onCompleted(Object o) {
                                        if (mDialog != null && mDialog.isShowing())
                                            mDialog.dismiss();
                                        ToastUtil.showCenterToast("NA成功！");
                                        mMainBottomPopupWindow.dismiss();
                                        setCurrentPage(mStep);
                                    }

                                    @Override
                                    public void onError() {
                                        if (mDialog != null && mDialog.isShowing())
                                            mDialog.dismiss();
                                        ToastUtil.showCenterToast("NA失败！");
//                            mMainBottomPopupWindow.dismiss();
                                    }
                                });
                            }
                        }
                    });
//                    String userId = SPUtil.getString(SPKey.Account.USER_ID);
//                    if (mDialog == null)
//                        mDialog = new LoadingDialog(SubRepairActivity.this);
//                    if (!mDialog.isShowing()) mDialog.show();
//                    StaticPresenter.stampNAInfo(userId, mBillId, mStepId, userId, stampId, naTypeId, new CallBack<Object>() {
//                        @Override
//                        public void onCompleted(Object o) {
//                            if (mDialog != null && mDialog.isShowing()) mDialog.dismiss();
//                            ToastUtil.showCenterToast("NA成功！");
//                            mMainBottomPopupWindow.dismiss();
//                            setCurrentPage(mStep);
//                        }
//
//                        @Override
//                        public void onError() {
//                            if (mDialog != null && mDialog.isShowing()) mDialog.dismiss();
//                            ToastUtil.showCenterToast("NA失败！");
////                            mMainBottomPopupWindow.dismiss();
//                        }
//                    });
                }
            });
        }
        mMainBottomPopupWindow.showAtLocation(mIvList, Gravity.BOTTOM, 0, 0);
        return mMainBottomPopupWindow;
    }

    private View initPopView(BottomPopType type) {
        switch (type) {
            case NA://N/A处理
                return LayoutInflater.from(this).inflate(R.layout.popwindow_na, null);
            case EngDisp://工程处理
                return LayoutInflater.from(this).inflate(R.layout.pop_engineering_disposal, null);
            case Seal://印章
                return LayoutInflater.from(this).inflate(R.layout.pop_seal, null);
            case Signature://签名
                return LayoutInflater.from(this).inflate(R.layout.pop_signature, null);
        }
        return null;
    }

    @Override
    public void onProgressItemClick(int index, boolean completed) {
        setCurrentPage(String.valueOf(index));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.ivList:
                if (mPopupWindow == null)
                    mPopupWindow = new MainListPopupWindow(this, false) {
                        @Override
                        public void showEPA() {
                            Intent intent = new Intent(SubRepairActivity.this, EngTreatmentEditActivity.class);
                            intent.putExtra("billId", mBillId);
                            intent.putExtra("stepId", mStepId);
                            intent.putExtra("woNo", mWoNo);
                            intent.putExtra("pn", mPn);
                            intent.putExtra("sn", mSn);
                            intent.putExtra("apn", mApn);
                            intent.putExtra("description", mDescription);
                            startActivity(intent);
                            mPopupWindow.dismiss();
                        }

                        @Override
                        public void showApply() {
//                            showBottomPopupWindow(BottomPopType.NA);
//                            mPopupWindow.dismiss();
                        }
                    };
                mPopupWindow.showAsDropDown(mIvList, Density.dip2px(this, -105f), Density.dip2px(this, 1f));
                break;
        }
    }

    public void showBigPic(ArrayList<String> data, int position) {
        Intent intent = new Intent(this, BigPicActivity.class);
        intent.putExtra("list", data);
        intent.putExtra("position", position);
        startActivity(intent);
    }

    public void closeBottomPop() {
        if (mMainBottomPopupWindow != null && mMainBottomPopupWindow.isShowing())
            mMainBottomPopupWindow.dismiss();
    }

    public void onNotLotDoubleClick(DataFilling item) {
        mSubProgressTitle.showSub(item.billType);
        mSubProgressTitle.setProgressStep(item.billType + 3);
        BaseFragment fragment = null;
        switch (item.billType) {
            case 1:
                fragment = new SubPartCheckFragment();
                break;
            case 2:
                fragment = new SubSetListFragment();
                break;
            case 3:
                fragment = new SubProcessListFragment();
                break;
        }
        if (fragment != null) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("data", item);
            bundle.putString("billId", mBillId);
            bundle.putString("id", item.id);
            fragment.setArguments(bundle);
            getSupportFragmentManager().beginTransaction().replace(R.id.flContainer, fragment).commit();
        }
    }

    @Override
    public void onNewIntent(Intent intent) {
        if (mCanCard && NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            tag = MCReader.patchTag(tag);
//            setTag(tag);
//            Utils.logUid(Utils.byte2Hex(tag.getId()));

            boolean isCopyUID = PreferencesUtil.getPreferences().getBoolean(
                    Constants.AutoCopyUID, false);
            if (isCopyUID) {
                int format = PreferencesUtil.getPreferences().getInt(
                        Constants.UIDFormat, 0);
                String fmtUID = Utils.byte2FmtString(tag.getId(), format);
            } else {
                // Show Toast message with UID.
                String msg = Utils.byte2Hex(tag.getId());
                LogUtil.i(msg);
                LoadingDialog loadingDialog = new LoadingDialog(this);
                loadingDialog.show();
                String userId = SPUtil.getString(SPKey.Account.USER_ID);
                StaticPresenter.getUserByCardId(userId, mBillId, stepId, msg, new CallBack<CardToSeal>() {
                    @Override
                    public void onCompleted(CardToSeal cardToSeal) {
                        loadingDialog.dismiss();
                        if (mNFCCallBack != null)
                            mNFCCallBack.onCallBack(cardToSeal.stamp, cardToSeal.userId);
                        if (mCardSealPop != null && mCardSealPop.isShowing())
                            mCardSealPop.dismiss();
                    }

                    @Override
                    public void onError() {
                        loadingDialog.dismiss();
                        if (mCardSealPop != null && mCardSealPop.isShowing())
                            mCardSealPop.dismiss();
                        ToastUtil.showCenterToast("获取印章失败！");
                    }
                });


            }
//            return Utils.checkMifareClassicSupport(tag, context);
        }
    }

    public void sealByCard(String id, NFCCallBack NFCCallBack) {
        if (NFCApp.hasWritePermissionToExternalStorage(SubRepairActivity.this)) {
            NFCApp.setUseAsEditorOnly(NFCApp.useAsEditorOnly());
            runStartUpNode(StartUpNode.FirstUseDialog);
            if (TextUtils.isEmpty(id))
                stepId = mStepId;
            else
                stepId = id;
            mNFCCallBack = NFCCallBack;
            if (mCardSealPop == null)
                mCardSealPop = new CardSealPop(this) {
                    @Override
                    protected void onDismiss1() {
                        mCanCard = false;
                    }
                };
            if (!mCardSealPop.isShowing())
                mCardSealPop.show();
//                mCardSealPop.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
            mCanCard = true;
        } else {
            ActivityCompat.requestPermissions(SubRepairActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                    1);
        }
    }

    @Override
    public void finish() {
        if (mCardSealPop != null && mCardSealPop.isShowing()) {
            mCardSealPop.dismiss();
            return;
        }
        super.finish();
    }
}
